<template>
  <div class="app-container">
    <!-- 桌面端布局 -->
    <el-row :gutter="20" v-if="!isMobile">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input v-model="deptName" placeholder="请输入部门名称" clearable size="small" prefix-icon="el-icon-search"
            style="margin-bottom: 20px" />
        </div>
        <div class="head-container">
          <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="true" :filter-node-method="filterNode"
            ref="tree" default-expand-all @node-click="handleNodeClick" />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="用户名称" prop="username">
            <el-input v-model="queryParams.username" placeholder="请输入用户名称" clearable size="small" style="width: 240px"
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="手机号码" prop="mobile">
            <el-input v-model="queryParams.mobile" placeholder="请输入手机号码" clearable size="small" style="width: 240px"
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="是否可登录" prop="is_active">
            <el-select v-model="queryParams.is_active" placeholder="是否可登录" clearable size="small" style="width: 240px"
              @change="handleQuery">
              <el-option v-for="dict in activeOptions" :key="dict.dictValue" :label="dict.dictLabel"
                :value="dict.dictValue" />
                
            </el-select>
          </el-form-item>
          <el-form-item label="用户状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="用户状态" clearable size="small" style="width: 240px"
              @change="handleQuery">
              <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel"
                :value="dict.dictValue" />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间" v-if="false">
            <el-date-picker v-model="dateRange" size="small" style="width: 240px" value-format="yyyy-MM-dd"
              type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
              v-hasPermi="['permission:user:post']">新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
              v-hasPermi="['permission:user:{id}:put']">修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
              v-hasPermi="['permission:user:{id}:delete']">删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport"
              v-hasPermi="['permission:user:import:post']">导入
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
              v-hasPermi="['permission:user:export:get']">导出
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" size="mini" @click="handleUpdateUser">更新用户</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="用户编号" align="center" key="id" prop="id" v-if="columns[0].visible" />
          <el-table-column label="用户名称" align="center" key="username" prop="username" v-if="columns[1].visible"
            :show-overflow-tooltip="true" />
          <el-table-column label="用户昵称" align="center" key="name" prop="name" v-if="columns[2].visible"
            :show-overflow-tooltip="true" />
          <el-table-column label="部门" align="center" key="deptName" prop="dept.name" v-if="columns[3].visible"
            :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <template v-if="scope.row.dept && scope.row.dept.length > 0">
                <div>
                  {{ scope.row.dept[0].name }}
                </div>
              </template>
              <template v-else>
                <span>无</span>
              </template>
            </template>
          </el-table-column>
          <el-table-column label="关联角色" align="center" key="role" prop="dept.role" v-if="columns[4].visible"
            :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <template v-if="scope.row.role.length > 0">
                <el-dropdown>
                  <span class="el-dropdown-link">{{ scope.row.role[0].name }}
                    <i class="el-icon-arrow-down el-icon--right"></i>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item v-for="role in scope.row.role" :key="role.id">{{ role.name }}</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
              <template v-else>
                <span>暂无关联角色</span>
              </template>
            </template>
          </el-table-column>
          <el-table-column label="手机号码" align="center" key="mobile" prop="mobile" v-if="columns[5].visible" width="120" />
          <el-table-column label="可登录" align="center" key="is_active" v-if="columns[6].visible" width="80">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.is_active"
                @change="handleStatusChange(scope.row)"
                v-hasPermi="['permission:user:{id}:put']">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="用户状态" align="center" key="status" v-if="columns[7].visible">
            <template slot-scope="scope">
              <span>{{ getStatusLabel(scope.row.status) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="create_time" v-if="columns[8].visible" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.create_time) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="220" class-name="small-padding fixed-width" 
            fixed="right"
            v-if="hasPermi([
            'permission:user:{id}:put',
            'permission:user:{id}:delete',
            'permission:user:resetpwd:put',
          ])
            ">
            <template slot-scope="scope">
              <div class="operation-buttons">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                  v-hasPermi="['permission:user:{id}:put']">修改
                </el-button>
                <el-button v-if="scope.row.id !== 1" size="mini" type="text" icon="el-icon-delete"
                  @click="handleDelete(scope.row)" v-hasPermi="['permission:user:{id}:delete']">删除
                </el-button>
                <el-button size="mini" type="text" icon="el-icon-key" @click="handleResetPwd(scope.row)"
                  v-hasPermi="['permission:user:resetpwd:put']">重置
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.page_size"
          @pagination="getList" />
      </el-col>
    </el-row>
    
    <!-- 移动端布局 -->
    <div v-if="isMobile" class="mobile-container">
      <!-- 移动端部门选择器 -->
      <div v-if="showDeptTree" class="mobile-tree-container">
        <div class="mobile-tree-header">
          <span :style="{ color: theme }">部门选择</span>
          <el-button 
            type="text" 
            icon="el-icon-arrow-up" 
            @click="showDeptTree = false" 
            :style="{ color: theme }">
            收起
          </el-button>
        </div>
        <el-input v-model="deptName" placeholder="请输入部门名称" clearable size="small" prefix-icon="el-icon-search"
          style="margin-bottom: 10px" />
        <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="true" :filter-node-method="filterNode"
          ref="mobileTree" default-expand-all @node-click="handleNodeClick" />
      </div>
      
      <!-- 移动端部门选择按钮 -->
      <div v-else class="mobile-tree-toggle">
        <el-button 
          type="primary" 
          size="small" 
          icon="el-icon-arrow-down"
          @click="showDeptTree = true"
          :style="{
            backgroundColor: theme,
            borderColor: theme,
            width: '100%',
            marginBottom: '10px',
            borderRadius: '4px',
            height: '36px'
          }">
          选择部门
        </el-button>
      </div>
      
      <!-- 移动端搜索表单 -->
      <div class="mobile-search-form">
        <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true" class="mobile-form">
          <el-form-item label="用户名称" prop="username">
            <el-input v-model="queryParams.username" placeholder="请输入用户名称" clearable size="small" style="width: 100%"
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="手机号码" prop="mobile">
            <el-input v-model="queryParams.mobile" placeholder="请输入手机号码" clearable size="small" style="width: 100%"
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="是否可登录" prop="is_active">
            <el-select v-model="queryParams.is_active" placeholder="是否可登录" clearable size="small" style="width: 100%"
              @change="handleQuery">
              <el-option v-for="dict in activeOptions" :key="dict.dictValue" :label="dict.dictLabel"
                :value="dict.dictValue" />
            </el-select>
          </el-form-item>
          <el-form-item label="用户状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="用户状态" clearable size="small" style="width: 100%"
              @change="handleQuery">
              <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel"
                :value="dict.dictValue" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery" :style="{
              backgroundColor: theme,
              borderColor: theme,
              width: '100%'
            }">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery" style="width: 100%; margin-top: 10px;">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 移动端操作按钮 -->
      <div class="mobile-action-buttons">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-button type="primary" plain icon="el-icon-plus" size="small" @click="handleAdd"
              v-hasPermi="['permission:user:post']" style="width: 100%">新增
            </el-button>
          </el-col>
          <el-col :span="12">
            <el-button type="success" plain icon="el-icon-edit" size="small" :disabled="single" @click="handleUpdate"
              v-hasPermi="['permission:user:{id}:put']" style="width: 100%">修改
            </el-button>
          </el-col>
        </el-row>
        <el-row :gutter="10" style="margin-top: 10px">
          <el-col :span="12">
            <el-button type="danger" plain icon="el-icon-delete" size="small" :disabled="multiple" @click="handleDelete"
              v-hasPermi="['permission:user:{id}:delete']" style="width: 100%">删除
            </el-button>
          </el-col>
          <el-col :span="12">
            <el-button type="info" plain icon="el-icon-upload2" size="small" @click="handleImport"
              v-hasPermi="['permission:user:import:post']" style="width: 100%">导入
            </el-button>
          </el-col>
        </el-row>
        <el-row :gutter="10" style="margin-top: 10px">
          <el-col :span="12">
            <el-button type="warning" plain icon="el-icon-download" size="small" @click="handleExport"
              v-hasPermi="['permission:user:export:get']" style="width: 100%">导出
            </el-button>
          </el-col>
          <el-col :span="12">
            <el-button type="primary" size="small" @click="handleUpdateUser" style="width: 100%">更新用户</el-button>
          </el-col>
        </el-row>
      </div>
      
      <!-- 移动端卡片列表 -->
      <div class="mobile-card-list">
        <el-card 
          v-for="(item, index) in userList" 
          :key="index"
          class="mobile-card"
          shadow="hover">
          <div class="mobile-card-header">
            <div class="card-title">
              <span class="name">{{ item.name }}</span>
              <span class="username">({{ item.username }})</span>
            </div>
            <div class="status-tag" :class="getStatusClass(item.status)">{{ getStatusLabel(item.status) }}</div>
          </div>
          
          <!-- 用户基本信息 -->
          <div class="mobile-card-info">
            <div class="info-item">
              <span class="info-label">手机号码：</span>
              <span class="info-value">{{ item.mobile || '未设置' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">部门：</span>
              <span class="info-value" v-if="item.dept && item.dept.length > 0">{{ item.dept[0].name }}</span>
              <span class="info-value" v-else>无</span>
            </div>
            <div class="info-item">
              <span class="info-label">角色：</span>
              <span class="info-value" v-if="item.role && item.role.length > 0">{{ item.role[0].name }}</span>
              <span class="info-value" v-else>无</span>
            </div>
            <div class="info-item">
              <span class="info-label">可登录：</span>
              <span class="info-value">
                <el-switch
                  v-model="item.is_active"
                  @change="handleStatusChange(item)"
                  v-hasPermi="['permission:user:{id}:put']">
                </el-switch>
              </span>
            </div>
            <div class="info-item">
              <span class="info-label">用户状态：</span>
              <span class="info-value">{{ getStatusLabel(item.status) }}</span>
            </div>
          </div>
          
          <!-- 展开查看更多信息 -->
          <div v-if="expandedCards.includes(index)" class="mobile-card-detail">
            <div class="info-item">
              <span class="info-label">创建时间：</span>
              <span class="info-value">{{ parseTime(item.create_time) }}</span>
            </div>
            <div v-if="item.role && item.role.length > 1" class="info-item">
              <span class="info-label">所有角色：</span>
              <div class="tag-list">
                <el-tag 
                  v-for="role in item.role" 
                  :key="role.id"
                  size="mini"
                  style="margin: 2px 4px 2px 0">
                  {{ role.name }}
                </el-tag>
              </div>
            </div>
          </div>
          
          <!-- 操作按钮 -->
          <div class="mobile-card-actions">
            <el-button type="text" @click="toggleExpand(index)">
              {{ expandedCards.includes(index) ? '收起' : '查看详情' }}
            </el-button>
            <div>
              <el-button type="text" @click="handleUpdate(item)" :style="{ color: theme }"
                v-hasPermi="['permission:user:{id}:put']">
                <i class="el-icon-edit"></i> 修改
              </el-button>
              <el-button v-if="item.id !== 1" type="text" @click="handleDelete(item)" style="color: #F56C6C"
                v-hasPermi="['permission:user:{id}:delete']">
                <i class="el-icon-delete"></i> 删除
              </el-button>
              <el-button type="text" @click="handleResetPwd(item)" :style="{ color: theme }"
                v-hasPermi="['permission:user:resetpwd:put']">
                <i class="el-icon-key"></i> 重置
              </el-button>
            </div>
          </div>
        </el-card>
      </div>
      
      <!-- 移动端分页 -->
      <div class="mobile-pagination" v-if="total > 0">
        <div class="mobile-pagination-wrapper">
          <!-- 第一行：总数和每页条数 -->
          <div class="pagination-row top-row">
            <span class="el-pagination__total">共 {{ total }} 条</span>
            <el-select 
              v-model="queryParams.page_size" 
              size="mini" 
              class="el-pagination__sizes"
              @change="handleSizeChange">
              <el-option
                v-for="item in [10, 20, 30, 50]"
                :key="item"
                :label="`${item}条/页`"
                :value="item">
              </el-option>
            </el-select>
          </div>
          
          <!-- 第二行：页码导航 -->
          <div class="pagination-row bottom-row">
            <el-pagination
              background
              @current-change="handleCurrentChange"
              :current-page="queryParams.page"
              :page-size="queryParams.page_size"
              layout="prev, pager, next, jumper"
              :total="total">
            </el-pagination>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :class="{'mobile-dialog': isMobile}">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item v-if="form.id == undefined" label="用户名" prop="username">
              <el-input v-model="form.username" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.id == undefined && showPWD" label="用户密码" prop="password">
              <el-input disabled v-model="form.password" placeholder="请输入用户密码" type="password" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户性别" prop="gender">
              <el-select v-model="form.gender" placeholder="请选择">
                <el-option v-for="dict in sexOptions" :key="dict.dictValue" :label="dict.dictLabel"
                  :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="归属部门" prop="dept">
              <treeselect v-model="form.dept" :options="deptOptions" :show-count="true" :multiple="true"
                :normalizer="normalizer" placeholder="请选择归属部门" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="主部门" prop="main_dept">
              <treeselect v-model="form.main_dept" :options="deptOptions" :show-count="true" :normalizer="normalizer"
                placeholder="请选择主部门" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="mobile">
              <el-input v-model="form.mobile" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="角色" prop="role">
              <el-select v-model="form.role" multiple filterable placeholder="请选择">
                <el-option v-for="item in roleOptions" :key="item.id" :label="item.name" :value="item.id"
                  :disabled="item.status == 0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="岗位" prop="post">
              <el-select v-model="form.post" multiple filterable placeholder="请选择">
                <el-option v-for="item in postOptions" :key="item.id" :label="item.name" :value="item.id"
                  :disabled="item.status == 0"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="可登录">
              <el-radio-group v-model="form.is_active">
                <el-radio v-for="dict in activeOptions" :key="dict.dictValue" :label="dict.dictValue">{{ dict.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户状态">
              <el-select v-model="form.status" placeholder="请选择用户状态">
                <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel"
                  :value="dict.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="管理员">
              <el-radio-group v-model="form.is_staff">
                <el-radio v-for="dict in activeOptions" :key="dict.dictValue" :label="dict.dictValue">{{ dict.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />
          是否更新已经存在的用户数据
          <el-link type="info" style="font-size: 12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入"xls"或"xlsx"格式文件！
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addUser,
  changeUserStatus,
  delUser,
  exportUser,
  getUser,
  importsUser,
  importTemplate,
  listUser,
  resetUserPwd,
  updateUser,
  registerUser,
  deptupdate
} from "@/api/vadmin/permission/user";
import { listPost } from "@/api/vadmin/permission/post";
import { listRole } from "@/api/vadmin/permission/role";
// import { comproomList } from "@/api/vadmin/config/room";
import { getToken } from "@/utils/auth";
import { listDept } from "@/api/vadmin/permission/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "User",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      showPWD: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 状态数据字典
      statusOptions: [
        { dictLabel: "已激活", dictValue: 1 },
        { dictLabel: "已禁用", dictValue: 2 },
        { dictLabel: "未激活", dictValue: 4 },
        { dictLabel: "退出企业", dictValue: 5 },
      ],
      // 激活数据字典
      activeOptions: [
        { dictLabel: "是", dictValue: true },
        { dictLabel: "否", dictValue: false },
      ],
      // 性别状态字典
      sexOptions: [
        {
          dictLabel: "None",
          dictValue: "-",
        },
        {
          dictLabel: "男",
          dictValue: "1",
        },
        {
          dictLabel: "女",
          dictValue: "2",
        },
      ],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 机房选项
      roomOptions: [],
      // 表单参数
      form: {
        avatar: "http://123.56.223.128:8080/media/avatar/default_7MVaIRf.jpg", //默认设置头像，不显示在表单中
      },
      defaultProps: {
        children: "children",
        label: "name",
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/admin/system/savefile/",
      },
      // 查询参数
      queryParams: {
        page: 1,
        page_size: 10,
        username: undefined,
        mobile: undefined,
        is_active: undefined,
        status: 1,
        dept: undefined,
      },
      // 列信息
      columns: [
        { key: 0, label: `用户编号`, visible: true },
        { key: 1, label: `用户名称`, visible: true },
        { key: 2, label: `用户昵称`, visible: true },
        { key: 3, label: `部门`, visible: true },
        { key: 4, label: `关联角色`, visible: true },
        { key: 5, label: `手机号码`, visible: true },
        { key: 6, label: `可登录`, visible: true },
        { key: 7, label: `用户状态`, visible: true },
        { key: 8, label: `创建时间`, visible: true },
      ],
      // 表单校验
      rules: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
        ],
        gender: [
          { required: true, message: "用户性别不能为空", trigger: "blur" },
        ],
        name: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
        role: [{ required: true, message: "角色不能为空", trigger: "blur" }],
        post: [{ required: true, message: "岗位不能为空", trigger: "blur" }],
        password: [
          { required: true, message: "用户密码不能为空", trigger: "blur" },
        ],
        main_dept: [
          { required: true, message: "主部门不能为空", trigger: "blur" },
        ],
        dept: [
          { required: true, message: "归属部门不能为空", trigger: "blur" },
        ],
        email: [
          {
            required: true,
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        mobile: [
          {
            required: true,
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
      },
      // 新增的移动端相关属性
      screenWidth: document.body.clientWidth,
      expandedCards: [],
      showDeptTree: false,
      mediaQueryList: null
    };
  },
  computed: {
    // 添加isMobile计算属性
    isMobile() {
      return this.screenWidth < 768;
    },
    theme() {
      return this.$store.state.settings.theme;
    }
  },
  created() {
    this.getList();
    this.getTreeselect();
    this.getPostData();
    this.getRoleData();
    // this.getRoomData();
    // this.getDicts("sys_normal_disable").then(response => {
    //   this.statusOptions = response.data;
    // });
    // this.getDicts("sys_user_sex").then((response) => {
    //   this.sexOptions = response.data;
    // });
    // this.getConfigKey("sys.user.initPassword").then((response) => {
    //   this.initPassword = response.msg;
    // });
    // 监听屏幕宽度变化
    this.mediaQueryList = window.matchMedia("(max-width: 768px)");
    this.mediaQueryList.addListener(this.handleScreenWidthChange);
  },
  beforeDestroy() {
    // 移除监听器
    if (this.mediaQueryList) {
      this.mediaQueryList.removeListener(this.handleScreenWidthChange);
    }
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      // console.log(11111, this.addDateRange(this.queryParams, this.dateRange));
      listUser(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          // console.log("用户", response.results);
          this.userList = response.results;
          this.total = response.count;
          this.loading = false;
        }
      );
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      listDept({ page: 1, page_size: 100000 }).then((response) => {
        // console.log("部门res", response);
        this.deptOptions = this.handleTree(response.results, "id");
        // console.log("部门", this.deptOptions);
      });
    },
    /** 查询岗位数据 */
    getPostData() {
      listPost({ page_size: 100000 }).then((response) => {
        // console.log("岗位", response);
        this.postOptions = response.results;
      });
    },

    /** 查询角色数据 */
    getRoleData() {
      listRole().then((response) => {
        this.roleOptions = response.results;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.dept = data.id;
      this.getList();
    },
    handleUpdateUser() {
      this.loading = true
      deptupdate().then(res => {
     
        this.loading = false
        this.msgSuccess("更新成功");
       
        this.getList()
      }).catch(err=>{

        this.loading = false
        this.msgError("更新失败");
      })
    },
    // 用户状态修改
    handleStatusChange(row) {
      console.log(111,row)
      let text = row.is_active == true ? "启用" : "停用";
      this.$confirm(
        '确认要"' + text + '""' + row.username + '"用户登录权限吗?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return changeUserStatus(row.id, row.is_active);
        })
        .then(() => {
          this.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.is_active = row.is_active === false ? true : false;
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        dept: undefined,
        username: undefined,
        name: undefined,
        password: "Meinn.cn!@#2022",
        password2: this.form.password,
        mobile: undefined,
        email: undefined,
        gender: undefined,
        is_active: true,
        status: 1,
        avatar: undefined,
        main_dept: undefined,
        is_staff: false,
        post: [],
        role: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.queryParams.dept = "";
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getTreeselect();
      // getUser().then((response) => {
      //   // this.postOptions = response.data.posts;
      //   // this.roleOptions = response.data.roles;

      // });
      this.open = true;
      this.title = "添加用户";
      this.form.password = this.initPassword;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      const id = row.id || this.ids;
      getUser(id).then((response) => {
        // console.log("修改获取用户信息", response);
        let data = response;
        data["post"] = response.post.map((item) => {
          return item.id;
        });
        data["role"] = response.role.map((item) => {
          return item.id;
        });
        data["dept"] = response.dept.map((item) => {
          return item.id;
        });

        if (response.main_dept !== null) {
          data["main_dept"] = response.main_dept.id;
        } else {
          data["main_dept"] = null;
        }
        // const reader = new FileReader();
        // reader.readAsDataURL(response.avatar);
        // console.log(111,)
        this.form = data;

        // console.log(" this.form>>>>", this.form);

        this.open = true;
        this.title = "修改用户信息";
        this.showPWD = false;
        delete this.form["password"];
      });
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.name + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(({ value }) => {
          const form = {
            id: row.id,
            new_password: value,
            confirm_password: value,
          };
          resetUserPwd(form).then((response) => {
            this.msgSuccess("修改成功，新密码是：" + value);
          });
        })
        .catch(() => { });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        // console.log(111, this.form);
        // this.form.main_dept = this.deptOptions.filter((res) => {
        //   if (this.form.main_dept == res.name) {
        //     return res.id;
        //   }
        // });
        // if (this.form.avatar == null || this.form.avatar == undefined) {
        //   this.form.avatar = require("@/assets/images/profile.png");
        // }
        // this.form delete avatar
        // let formData = new FormData();
        // formData.append("file", this.form.avatar);
        // console.log(888, formData, this.form);
        delete this.form.avatar
        if (valid) {
          if (this.form.id !== undefined) {
            // console.log("修改", this.form);
            updateUser(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            (this.form.password = this.form.password2 = "Meinn.cn!@#2022"),
              // console.log("新增", this.form);
              addUser(this.form).then((response) => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
          }
        }
      });
    },
    /** 新增用户时，先注册用户 */
    // handleRegister() {
    //   const data = {
    //     first_name: "",
    //     last_name: "",
    //     name: this.form.name,
    //     email: this.form.email,
    //     mobile: this.form.mobile,
    //     password: this.form.password,
    //     password2: this.form.password,
    //     username: this.form.username,
    //   };
    //   registerUser(data).then((res) => {
    //     this.msgSuccess("新增成功");
    //     this.open = false;
    //     this.getList();
    //   });
    // },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.id || this.ids;
      this.$confirm(
        '是否确认删除用户编号为"' + userIds + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delUser(userIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },

    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有用户数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportUser(queryParams);
        })
        .then((response) => {
          this.download(response.data.file_url, response.data.name);
        });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then((response) => {
        this.download(response.data.file_url, response.data.name);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      // 是否更新已经存在的用户数据
      importsUser({
        file_url: response.data.file_url,
        updateSupport: this.upload.updateSupport,
      }).then((response) => {
        this.$alert("导入成功！", "导入结果", {
          dangerouslyUseHTMLString: true,
        });
        this.getList();
      });
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 获取状态标签
    getStatusLabel(status) {
      const statusMap = {};
      this.statusOptions.forEach(item => {
        statusMap[item.dictValue] = item.dictLabel;
      });
      return statusMap[status] || '未知状态';
    },
    // 获取状态样式类
    getStatusClass(status) {
      const statusClassMap = {
        1: 'active',    // 已激活
        2: 'inactive',  // 已禁用
        4: 'pending',   // 未激活
        5: 'exited'     // 退出企业
      };
      return statusClassMap[status] || 'unknown';
    },
    // 新增的移动端相关方法
    // 处理屏幕宽度变化
    handleScreenWidthChange(e) {
      this.screenWidth = document.body.clientWidth;
    },
    // 切换卡片展开状态
    toggleExpand(index) {
      const position = this.expandedCards.indexOf(index);
      if (position !== -1) {
        this.expandedCards.splice(position, 1);
      } else {
        this.expandedCards.push(index);
      }
    },
    // 处理分页大小变化
    handleSizeChange(val) {
      this.queryParams.page_size = val;
      this.getList();
    },
    // 处理页码变化
    handleCurrentChange(val) {
      this.queryParams.page = val;
      this.getList();
    }
  },
};
</script>

<style lang="scss" scoped>
.operation-buttons {
  display: flex;
  justify-content: space-around;
  white-space: nowrap;
  
  .el-button {
    padding: 5px;
    margin-left: 0;
    margin-right: 0;
  }
}

/* 移动端样式 */
@media screen and (max-width: 768px) {
  .mobile-container {
    padding: 0;
  }

  .mobile-form {
    .el-form-item {
      width: 100%;
      margin-bottom: 15px;
    }
  }
  
  .mobile-search-form {
    margin-top: 10px;
  }
  
  .mobile-action-buttons {
    margin-top: 10px;
    margin-bottom: 15px;
  }
  
  .mobile-card-list {
    margin-top: 15px;
    
    .mobile-card {
      margin-bottom: 15px;
      
      .mobile-card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;
        padding-bottom: 10px;
        border-bottom: 1px solid #f0f0f0;

        .card-title {
          font-size: 16px;
          font-weight: bold;
          
          .name {
            color: #303133;
          }
          
          .username {
            font-size: 14px;
            color: #909399;
            margin-left: 5px;
          }
        }
        
        .status-tag {
          padding: 2px 8px;
          border-radius: 10px;
          font-size: 12px;
          color: #fff;
          
          &.active {
            background-color: #67c23a;
          }
          
          &.inactive {
            background-color: #909399;
          }
          
          &.pending {
            background-color: #e6a23c;
          }
          
          &.exited {
            background-color: #f56c6c;
          }
          
          &.unknown {
            background-color: #909399;
          }
        }
      }
      
      .mobile-card-info {
        margin-bottom: 10px;
        
        .info-item {
          display: flex;
          margin-bottom: 8px;
          
          .info-label {
            color: #606266;
            font-size: 14px;
            min-width: 80px;
          }
          
          .info-value {
            font-size: 14px;
            word-break: break-all;
          }
          
          .tag-list {
            display: flex;
            flex-wrap: wrap;
          }
        }
      }
      
      .mobile-card-detail {
        background-color: #f9f9f9;
        padding: 10px;
        margin: 10px 0;
        border-radius: 4px;
        
        .info-item {
          display: flex;
          margin-bottom: 8px;
          
          .info-label {
            color: #606266;
            font-size: 14px;
            min-width: 80px;
          }
          
          .info-value {
            font-size: 14px;
            word-break: break-all;
          }
        }
      }
      
      .mobile-card-actions {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 15px;
        padding-top: 10px;
        border-top: 1px solid #ebeef5;
        
        .el-button {
          padding: 0;
          margin-right: 15px;
          
          &:last-child {
            margin-right: 0;
          }
        }
      }
    }
  }
  
  .mobile-pagination {
    margin-top: 20px;
    
    .mobile-pagination-wrapper {
      .pagination-row {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
        
        .el-pagination__sizes {
          width: 100px;
        }
      }
      
      .bottom-row {
        display: flex;
        justify-content: center;
        
        .el-pagination {
          padding: 0;
          text-align: center;
        }
      }
    }
  }
  
  .mobile-tree-container {
    background-color: #fff;
    padding: 10px;
    margin-bottom: 15px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    
    .mobile-tree-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-bottom: 10px;
      border-bottom: 1px solid #ebeef5;
      margin-bottom: 10px;
      
      span {
        font-weight: bold;
        font-size: 16px;
      }
    }
  }
  
  .mobile-dialog {
    .el-dialog__body {
      padding: 15px !important;
    }
    
    .el-form-item {
      margin-bottom: 15px;
    }
    
    .dialog-footer {
      .el-button {
        width: 100%;
        margin-left: 0 !important;
        margin-bottom: 10px;
      }
    }
    
    .el-select,
    .treeselect {
      width: 100% !important;
    }
  }
}
</style>

